package com.jzz.eletuanbackend.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.jzz.eletuanbackend.entity.Block;
import com.jzz.eletuanbackend.entity.Commodity;
import com.jzz.eletuanbackend.entity.CustomerShop;
import com.jzz.eletuanbackend.entity.Order;
import com.jzz.eletuanbackend.mapper.CustomerMapper;
import com.jzz.eletuanbackend.mapper.OrderMapper;
import com.jzz.eletuanbackend.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DelivererService delivererService;

    public Msg allShops() {
        return Msg.ok(customerMapper.allShops());
    }

    public Msg shop(Long shopId) {
        // 获取所有的板块以及各版块下的商品信息
        List<Block> blocks = customerMapper.shop(shopId);
        CustomerShop basicInfo = customerMapper.shopBasicInfo(shopId);
        JSONObject object = (JSONObject) JSON.toJSON(basicInfo);
        object.put("blocks", blocks);
        return Msg.ok(object);
    }

    public Msg pay(Long userId, Long orderId) {
        Integer result = orderMapper.pay(orderId, System.currentTimeMillis(), userId);
        if (result > 0) {
            return Msg.ok("支付成功");
        } else {
            return Msg.err(-1, "无法支付非本人订单");
        }
    }

    /* specifications: [ { name: "选规格", spec: { "微辣": 0.0, "不辣": 0.0, "加孜然": 0.5 } } ] */
    /* commodities: [ { id: 1002, quantity: 1, spec: [ "微辣" ] } ] */
    @Transactional
    public Msg submitOrder(Long userId, String commodities, String receiveInfo) {
        Long shopId = -1L;
        Double shipPrice = 0.0;
        Double packPrice = 0.0;
        Double commPrice = 0.0;
        try {
            JSONArray array = JSON.parseArray(commodities);

            // Each commodity
            // 记录每条内容的名称、规格、数量、图片、价格
            JSONArray commodityArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {
                Commodity commodity = customerMapper.getCommodity(array.getJSONObject(i).getLong("id"));
                Integer quantity = array.getJSONObject(i).getInteger("quantity");
                JSONArray userSpecs = array.getJSONObject(i).getJSONArray("spec");
                JSONArray specs = JSON.parseArray(commodity.getSpecifications());
                JSONObject c = new JSONObject();

                StringBuilder displaySpecification = new StringBuilder();

                if (userSpecs.size() != specs.size()) {
                    return Msg.err(-1, "商品信息错误");
                }

                double additionalPrice = 0.0;
                for (int j = 0; j < userSpecs.size(); j++) {
                    additionalPrice += specs.getJSONObject(j).getJSONObject("spec").getDoubleValue(userSpecs.getString(j));
                    displaySpecification.append(userSpecs.getString(j));

                    if (j != userSpecs.size() - 1) {
                        displaySpecification.append(" / ");
                    }
                }

                Long sid = customerMapper.getShopIdByCommodity(commodity.getId());
                if (shopId == -1L) {
                    shopId = sid;
                } else {
                    if (!shopId.equals(sid)) {
                        throw new JSONException();
                    }
                }

                packPrice += commodity.getPackPrice() * quantity;
                commPrice += (commodity.getPrice() + additionalPrice) * quantity;

                // 记录信息
                c.put("name", commodity.getName());
                c.put("spec", displaySpecification.toString());
                c.put("image", commodity.getImage());
                c.put("quantity", quantity);
                c.put("price", commodity.getPrice() + additionalPrice);
                c.put("packPrice", commodity.getPackPrice());
                commodityArray.add(c);
            }

            shipPrice = customerMapper.getShipPrice(shopId);

            Integer result = orderMapper.newOrder(userId, shopId, JSON.toJSONString(commodityArray), System.currentTimeMillis(),
                    false, shipPrice, receiveInfo, packPrice, commPrice + packPrice + shipPrice);
            if (result == 0) {
                return Msg.err(-1, "店铺未营业");
            }
        } catch (JSONException e) {
            return Msg.err(-1, "错误的请求格式");
        }

        return Msg.ok("下单成功");
    }

    @Transactional
    public Msg cancelOrder(Long userId, Long id) {
        if (orderMapper.isOrderDelivered(id) == 0) {
            Integer result = orderMapper.cancelOrder(id, userId, System.currentTimeMillis());
            if (result > 0) {
                return Msg.ok("取消成功");
            } else {
                return Msg.err(-1, "无法取消非本人订单");
            }
        } else {
            return Msg.err(-1, "正在配送，无法取消订单");
        }
    }

    public Msg getPosition(Long userId, Long orderId) {
        Order order = orderMapper.getById(orderId);

        if (!userId.equals(order.getCustomerId())) {
            return Msg.err(-1, "不能查看非本人订单");
        }

        if (order.getCancelTime() != 0) {
            return Msg.err(-1, "订单已取消");
        } else if (order.getReceiveTime() != 0) {
            return Msg.err(-1, "订单已完成");
        }

        JSONObject object = new JSONObject();
        JSONObject shop = new JSONObject();
        shop.put("lng", order.getShopLongitude());
        shop.put("lat", order.getShopLatitude());

        object.put("shop", shop);

        if (order.getDelivererId() != null) {
            JSONObject deliverer = new JSONObject();
            JSONObject getDeliverer = (JSONObject) delivererService.getPosition(order.getDelivererId()).getData();
            deliverer.put("lng", getDeliverer.getDouble("longitude"));
            deliverer.put("lat", getDeliverer.getDouble("latitude"));
            object.put("deliverer", deliverer);
        }

        return Msg.ok("success", object);
    }

    public Msg getOrder(Long orderId) {
        return Msg.ok("success", orderMapper.getById(orderId));
    }

    public Msg getAllOrders(Long userId) {
        return Msg.ok("success", orderMapper.getByCustomerId(userId));
    }

    public Msg commentOrder(Long orderId, String shopComment, String delivererComment,
                            Integer shopStar, Integer deliverStar) {
        try {
            Integer result = orderMapper.commentOrder(orderId, shopComment, delivererComment, shopStar, deliverStar);
            if (result > 0) {
                return Msg.ok("评价成功");
            } else {
                return Msg.err(-1, "不允许重复评价");
            }
        } catch (Exception e) {
            return Msg.err(-1, "不允许重复评价");
        }
    }

    public Msg editReceiveInfo(Long userId, String receiveInfo) {
        /* [ { location: '山东大学软件学院', rname: '习强国', rphone: '110' } ] */
        Integer result = customerMapper.editReceiveInfo(userId, receiveInfo);
        if (result > 0) {
            return Msg.ok("修改成功");
        } else {
            return Msg.err(-1, "修改失败");
        }
    }

    public Msg info(Long userId) {
        return Msg.ok("success", customerMapper.info(userId));
    }
}
